package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.admin.entity.Wxjq;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.biz.api.entity.WxReserve;
import com.oceansoft.mobile.biz.api.service.ApiHzyyServiceImpl;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.base.entity.Pager;
import com.oceansoft.mobile.common.base.entity.Query;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.weixin.util.DesUtil;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;


import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;

@Controller
@RequestMapping("api/personal")
public class ApiPersonalController {
    @Resource
    private ApiHzyyServiceImpl apiHzyyService;
    @ResponseBody
    @RequestMapping(value = "GetPersonalBJ")
    public Result GetPersonalBJ(HttpServletRequest request) throws IllegalArgumentException, Exception {
        Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
        if (null == member) {
            return new Result(600, "您当前未登陆,请返回登陆！");
        }
        Map<String, String> param = new HashMap<String, String>();
        param.put("UserGuid", member.getGuid());
		param.put("BJzt",String.valueOf(Integer.parseInt(request.getParameter("BJzt")) +2));
//        param.put("BJzt", "1");
        param.put("PageIndex", request.getParameter("PageIndex"));
        param.put("PageSize", "10");
        System.out.println("param====" + param);
        String url = Constant.host5 + "api/GetPersonalBJ/GetPersonalBJ";
        Result re = JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
        System.out.println(JSONObject.toJSON(re));
        return re;
    }

    @ResponseBody
    @RequestMapping(value = "updateUser")
    public Result updateUsersubmit(HttpServletRequest request) throws IllegalArgumentException, Exception {
        String openId = (String) request.getSession().getAttribute("openId"); //WeixinUtil.getOpenId(request);;//"20881011910123570328892602119985",
        String source = request.getParameter("source");
        if(!StringUtils.isEmpty(source)&&"szgaapp".equals(source))
        {
        	openId = request.getParameter("appcode");
        }
        Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
        if(member==null)
        {
        	com.alibaba.fastjson.JSONObject json= com.alibaba.fastjson.JSONObject.parseObject("{ \"OpenId\":\"" + openId + "\",  \"UserSource\":1}");
    		String a = "";
    		try {
    			a = HttpClientUtil.post(Constant.host5+WeixinUtil.USERAUTH_URL, json);
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
    		com.alibaba.fastjson.JSONObject jsona= com.alibaba.fastjson.JSONObject.parseObject(a);
    		//String openId = (String)sessiion.getAttribute("openId");
    		/**
    		 *如果是绑定用户，存session，把用户信息放到session里
    		 */
			if((Boolean)jsona.get("succ")){
				try {
					member =WeixinUtil.SetMember(com.alibaba.fastjson.JSONObject.parseObject(jsona.get("data").toString()));
					member.setOpenId(openId);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
        }
        if(null==member)
        {
        	Result result = new Result();
        	result.setSucc(false);
        	result.setMsg("用户更新失败");
        	return result;
        }
        	
        
        Map<String, String> param = new HashMap<String, String>();
        JSONObject json = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        DesUtil tools = new DesUtil();
        param = RequestUtils.buildParamsByNamesFromRequest(request);
        List<JSONObject> list = new ArrayList<JSONObject>();
        //真实姓名
        json.put("UpType", "4");
        json.put("UpValue", param.get("realName"));
        list.add(json);
        //身份证号
        json = new JSONObject();
        json.put("UpType", "21");
        json.put("UpValue", tools.encode(param.get("idCard")));
        list.add(json);
        //联系地址
        json = new JSONObject();
        json.put("UpType", "3");
        json.put("UpValue", param.get("address"));
        list.add(json);
        //联系人
        json = new JSONObject();
        json.put("UpType", "14");
        json.put("UpValue", param.get("contacts"));
        list.add(json);
        //手机号码
        json = new JSONObject();
        json.put("UpType", "1");
        json.put("UpValue", tools.encode(param.get("mobile")));
        list.add(json);
        String url = Constant.host5 + "api/Users/UpdateUserMsg";
        jsonObject.put("OpenId", openId);
        jsonObject.put("UserSource", "3");
        jsonObject.put("list", list);
        Result result = JSONObject.parseObject(HttpClientUtil.post(url, jsonObject), Result.class);
        if(result.isSucc()){
            member.setRealName(param.get("realName"));
            member.setAddress(param.get("address"));
            member.setIdCard(param.get("idCard"));
            member.setContacts(param.get("contacts"));
            member.setMobile(param.get("mobile"));
            request.getSession().setAttribute(Constant.SESSION_USER,member);
        }
        return result;
    }

    /**
     * 注销用户，删除网厅的绑定关系
     *
     * @param request
     * @return
     * @throws IllegalArgumentException
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "userszx")
    public Result userszx(HttpServletRequest request) throws IllegalArgumentException, Exception {
        Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
        String openId = (String)request.getSession().getAttribute("openId");
        if (null == member) {
            return new Result(600, "您当前未登陆,请返回登陆！");
        }
        String url = Constant.host5 + "api/Users/Userszx?userguid=" + member.getGuid() + "&openid=" + openId;
        Result result = JSONObject.parseObject((HttpClientUtil.doGet(url)), Result.class);
        if(result.isSucc()){
            request.getSession().removeAttribute(Constant.SESSION_USER);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("modifyPassword")
    public Result modifyPassword(HttpServletRequest request) throws IllegalArgumentException, Exception {
        Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
//        String openId = (String)request.getSession().getAttribute("openId");
        String data= (String)request.getParameter("jsondata");
        JSONObject json=JSONObject.parseObject(data);
        String userName = "";
        if(null==member)
        {
        	userName = (String)json.get("USERNAME");
        }
        else
        {
        	userName = member.getLoginId();
        }
        if (null == userName) {
            return new Result(600, "您当前未登陆,请返回登陆！");
        }
        data =  URLDecoder.decode(data,"utf-8");
        String oldPassword=(String)json.get("OLDPASSWORD");
        String password=(String)json.get("PASSWORD");


        DesUtil tools = new DesUtil();
        Map<String,String> param=new HashMap<String,String>();
        param.put("newpwd",tools.encode(password).toString());
        param.put("userSource","3");
        param.put("username",userName);
        param.put("oldpwd",tools.encode(oldPassword).toString());


        String str = HttpClientUtil.doPost("http://172.16.1.101:8080/api/Users/UpdatePwd",param,"utf-8");

        Result result =JSONObject.parseObject(str,Result.class);
        return result;
    }
    /**
     * 新增一个需要登录的跳转控制
     *
     * @return
     */
    @RequestMapping(value = "gotopageWithUser/{pageName}")
    public String gotoMattersPageWithUser(@PathVariable("pageName") String pageName, HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
        boolean b = WeixinUtil.checkIsLoginUser(request);
        String source = (String) request.getSession().getAttribute("source");
	       if (StringUtils.isNotBlank(source)) {
	       	model.addAttribute("source", source);
	       }
        if (!b) {
            model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
            model.addAttribute("gotoPage", "/api/personal/gotopageWithUser/" + pageName);
            return "weixin/login/login";
        } else {
            Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
            if(pageName.equals("personalcenter")){
            	try{
            	String url="http://172.16.1.101:8080/api/users/JGOpenID?OpenId="+member.getOpenId();
            	JSONObject obj=JSONObject.parseObject(HttpClientUtil.doGet(url));
            	JSONObject o=obj.getJSONObject("data");
            	//System.out.println("####网厅返回结果:"+obj.toString());
            	//System.out.println("####网厅返回结果:"+o.toString());
            	model.addAttribute("ststus", o.get("SMXX"));}catch(Exception e){
            		model.addAttribute("ststus", member.getSmxx());	
            	}
            }
            model.addAttribute("data", member);
            return "weixin/personalcenter/" + pageName;
        }
    }
    
    /**
     *跳转办件详情页面
     *
     * @return
     */
    @RequestMapping(value = "/detail/{id}/{ind}/{bjbh}")
    public String gotoPageWithUser(@PathVariable("id") String id,@PathVariable("ind") String ind,@PathVariable("bjbh") String bjbh, HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
    	model.addAttribute("id", id);
    	model.addAttribute("ind", ind);
    	model.addAttribute("bjbh", bjbh);
        model.addAttribute("source",request.getParameter("source"));
        return "weixin/personalcenter/wdbjxq";
    }
    
    @RequestMapping(value = "/detailxq/{id}")
    public Result GetPersonalBJDetail(HttpServletRequest request,@PathVariable("id") String id) throws IllegalArgumentException, Exception {
        String url = Constant.host5 + "api/Progress/Detail?prjNo="+id;
        Result re = JSONObject.parseObject((HttpClientUtil.doGet(url)), Result.class);
        System.out.println(JSONObject.toJSON(re));
        return re;
    }
    @RequestMapping(value = "/detailxq_2/{bjbh}/{type}")
    public Result GetPersonalBJDetail_2(HttpServletRequest request,@PathVariable("bjbh") String bjbh,@PathVariable("type") String type) throws IllegalArgumentException, Exception {
        String url = Constant.host5 + "api/hclstxz/hclsprint?proguid="+bjbh+"&type="+type;
        Result r = JSONObject.parseObject((HttpClientUtil.doGet(url)), Result.class);
        System.out.println(JSONObject.toJSON(r));
        return r;
    }
    @ResponseBody
    @RequestMapping(value = "GetPersonalYYBJ")
    public Result GetPersonalYYBJ(HttpServletRequest request) throws IllegalArgumentException, Exception {
        Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
        if (null == member) {
            return new Result(600, "您当前未登陆,请返回登陆！");
        }
        if(member.getOpenId()==""||member.getOpenId()==null||member.getOpenId().equals("null")){
            member.setOpenId((String)request.getSession().getAttribute("openId"));
        }
      /*  Map<String, String> param = new HashMap<String, String>();
        param.put("UserGuid", member.getGuid());
        param.put("BJzt",String.valueOf(Integer.parseInt(request.getParameter("BJzt")) +2));
//        param.put("BJzt", "1");
        param.put("PageIndex", request.getParameter("PageIndex"));
        param.put("PageSize", "10");
        System.out.println("param====" + param);
        String url = Constant.host5 + "api/GetPersonalBJ/GetPersonalBJ";
        Result re = JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
        System.out.println(JSONObject.toJSON(re));*/
        Query query=new Query();
        query.setPage(Integer.parseInt(request.getParameter("PageIndex")));
        query.setRows(10);
        Pager<WxReserve> pager = apiHzyyService.getWxReserve(member.getGuid(),query);
        Result re=new Result();
        re.setData(pager.getRows());
        return re;
    }
    @RequestMapping(value = "signs/{pageName}",method = RequestMethod.POST)
    public String gotoSignsPage(@PathVariable("pageName")String pageName, HttpServletRequest request,Model model) {
        try{
                String signs= request.getParameter("signs");
                model.addAttribute("detail",JSONObject.parseObject(signs));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "weixin/personalcenter/wdyyxq";
    }
    /**
     * 户政全流程，EMS地址填写
     */
    @RequestMapping(value = "/gotoEMSPage/{projectGuid}/{CASENAME}/{CASENO}")
    public String gotoEMSPage(@PathVariable("projectGuid")String projectGuid,@PathVariable("CASENAME")String CASENAME,@PathVariable("CASENO")String CASENO, HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
       model.addAttribute("projectGuid",projectGuid);
       model.addAttribute("CASENAME",CASENAME);
       model.addAttribute("CASENO",CASENO);
        return "weixin/personalcenter/jd";
    }
    /**
     * 户政邮寄地址提交
     */
    @ResponseBody
    @RequestMapping(value = "jdtj")
    public Result jdtj(HttpServletRequest request) throws IllegalArgumentException, Exception {
        String url=Constant.host5+"api/Product/SaveEMS";
        Map<String, String> param = new HashMap<String, String>();
        param.put("projectGuid",request.getParameter("projectGuid"));
        param.put("CASENAME",request.getParameter("CASENAME"));
        param.put("CASENO",request.getParameter("CASENO"));
        param.put("sendPostCode",request.getParameter("sendPostCode"));
        param.put("sendLinkName",request.getParameter("sendLinkName"));
        param.put("sendAddress",request.getParameter("sendAddress"));
        param.put("sendMobile",request.getParameter("sendMobile"));
        param.put("obtPostCode",request.getParameter("obtPostCode"));
        param.put("obtLinkName",request.getParameter("obtLinkName"));
        param.put("obtAddress",request.getParameter("obtAddress"));
        param.put("obtMobile",request.getParameter("obtMobile"));
        param.put("ISSL",request.getParameter("ISSL"));
        Result re = JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
        return re;
    }
    /**
     * 户政办件流程展示
     */
    @RequestMapping(value = "/gotoShowLCPage")
    public String gotoShoeLCPage( HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
       model.addAttribute("sbsj",request.getParameter("sbsj"));
       model.addAttribute("bjslsj",request.getParameter("bjslsj"));
       model.addAttribute("bjslyj",request.getParameter("bjslyj"));
       model.addAttribute("spjgsj",request.getParameter("spjgsj"));
       model.addAttribute("spjgyj",request.getParameter("spjgyj"));
       model.addAttribute("clsdsj",request.getParameter("clsdsj"));
       model.addAttribute("zt",request.getParameter("zt"));
        model.addAttribute("bjsj",request.getParameter("bjsj"));
        return "weixin/personalcenter/jd_flow";
    }
}
